<template>
  <div class="content-container" ref="content-container">
    <div class='mask' v-show="isFullscreen" @click="isFullscreen=false"></div>
    <div class="content" ref="content">
      <div class="chart-container" v-loading="pageLoading">
        <div class="function-area" style="align-items: flex-end;">
          <el-form label-width="100px"  label-position="left">
            <el-form-item label="模式">
              <el-select v-model="mode1" placeholder="请选择模式1" size="mini">
                <el-option
                    v-for="(v,k) in dateMap"
                    :key="'mode1-'+k"
                    :value="k">
                </el-option>
              </el-select>
              <span style="padding: 0 15px">—</span>
              <el-select v-model="mode2" placeholder="请选择模式2" size="mini">
                <el-option
                    v-for="(v,k) in dateMap"
                    :key="'mode1-'+k"
                    :value="k">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期">
              <date-picker v-model="startDate" placeholder="请选择开始日期" size="mini" :dateOptions="dateOptions"/>
              <span style="padding: 0 15px">到</span>
              <date-picker v-model="endDate" placeholder="请选择结束日期" size="mini" :dateOptions="dateOptions"/>
            </el-form-item>
            <el-form-item label="可选区域">
              <el-select v-model="selectedArea" multiple placeholder="请选择区域" size="mini" style="width:100%;">
                <el-option
                    v-for="item in optionalArea"
                    :key="item"
                    :label="item"
                    :value="item">
                </el-option>
              </el-select>
            </el-form-item>
<!--            <el-button type="primary" @click="addCard">新增评分卡</el-button>-->
            <el-button type="primary" @click="refreshCard">刷新评分卡</el-button>
          </el-form>

          <div class="output score">
            <el-form label-width="70px" label-position="left">
              <el-form-item label="样式：">
                <el-select v-model="scoreMode" placeholder="请选择样式" size="mini">
                  <el-option value="颜色"></el-option>
                  <el-option value="符号"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <ExportImage style="margin-bottom: 18px;"
                         el="#cards-box"
                         name="score card"
                         :valid="cards.score.length>0"
                         warning="请先绘制选项卡"
                         :prepare="exportPrepare"
                         :finish="exportFinish"
            />
            <div style="display: flex; justify-content: space-between;">
                            <span class="desc-btn" @click="showConfidence">
                                <i class="el-icon-info"></i>
                                评分卡说明
                            </span>
              <el-tooltip class="item" effect="dark" content="全屏显示评分卡，点击边缘关闭全屏" placement="bottom-end">
                                <span class="desc-btn" @click="isFullscreen = true" v-show="!isFullscreen && cards.score.length">
                                    <i class="el-icon-full-screen"></i>
                                    全屏显示
                                </span>
              </el-tooltip>

            </div>
            <el-dialog title="评分卡说明"  width="650px" :visible.sync="cardDescription.show">
              <div v-loading="cardDescription.loading" element-loading-background="#FFFFFF">
                <div class="desc-line"><b>The time range is from {{timeSeries[0]}} to {{timeSeries[timeSeries.length-1]}}.</b></div>
                <div class="desc-line" v-for="cd in cardDescription.list" :key="cd.color">
                  <div class="desc-color" :style="{backgroundColor: cd.color}"></div>
                  <div class="desc-symbol" :style="{backgroundImage: `url(${cd.symbol})`}"></div>
                  <div class="desc-text">{{descFilter(cd.text)}}</div>
                </div>
              </div>
            </el-dialog>
          </div>
        </div>


        <div :class="{'drawing-board': true, 'fullscreen': isFullscreen}" ref="drawing-board" v-loading="loading">
          <div class="status" v-show="!cardVisible" @click="addCard">
            <a>
              <img :src="imgBrush" height="100">
              <div>
                <span>开始绘制</span>
                <span>start  drawing</span>
              </div>
            </a>
          </div>
          <div id="cards-box" ref="cards-box" v-if="cards.score.length">
            <ScoreIndex :levels="levels" style="width: 80px; display:inline-block"/>
            <card v-for="idx in cards.score.length"
                  :key="`card-${idx}`"
                  :score="cards.score[idx-1]"
                  :area="cards.area[idx-1]"
                  :mode1="cards.mode1[idx-1]"
                  :mode2="cards.mode2[idx-1]"
                  :dates-list="cards.datesList[idx-1]"
                  :scoreMode="scoreMode"
                  :style="{width: cardWidth}"
                  :levels="levels"
                  :time-series="timeSeries"
                  :options="options"
                  class="card"/>
            <div style="display:none" ref="desc-bottom">
              <div class="desc-line"><b>The time range is from {{timeSeries[0]}} to {{timeSeries[timeSeries.length-1]}}.</b></div>
              <div style="margin-left: 30px" class="desc-line" v-for="cd in cardDescription.list" :key="cd.color">
                <div class="desc-color" :style="{backgroundColor: cd.color}"></div>
                <div class="desc-symbol" :style="{backgroundImage: `url(${cd.symbol})`}"></div>
                <div class="desc-text">{{descFilter(cd.text)}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { scdCard, pageLoadInfo, scdCardGetConfidence} from '@/api/grapesRegionDeterm/grapesRegionDeterm';
import imgBrush from '@/assets/img/brush.svg';
import DatePicker from '@/components/common/DatePicker.vue';
import Card from '@/components/ScoreCard/Card.vue';
import ScoreIndex from '@/components/ScoreCard/ScoreIndex.vue';
import ExportImage from '@/components/common/ExportImage.vue'

import score_3 from '@/assets/img/score_card/score_3.svg';
import score_2 from '@/assets/img/score_card/score_2.svg';
import score_1 from '@/assets/img/score_card/score_1.svg';
import score0 from '@/assets/img/score_card/score0.svg';
import score1 from '@/assets/img/score_card/score1.svg';
import score2 from '@/assets/img/score_card/score2.svg';
import score3 from '@/assets/img/score_card/score3.svg';
import config from "@/config";

// 评分卡说明顺序是从好到低，需要反转
const colors = config.SCD_COLORS.reverse();
const symbols = config.SCD_SYMBOLS.reverse();

// 两个评分卡不同的参数
const levels = [1000, 850, 700, 500, 400, 300, 200, 100];
const timeSeries = [24, 48, 72];
const options = ['BIAS', 'RMSE', 'STD'];
const dateMap = {
  'MESO3km': [],
  'MESO10km': [],
  'TYM': [],
};
const optionalArea = ['China(15-60,70-145)'];

export default {
  name: 'ScoreCard',
  components: {
    DatePicker,
    Card,
    ScoreIndex,
    ExportImage,
  },
  data(){
    return{
      pageLoading: true, // 页面加载
      loading: false, // 绘图加载
      imgBrush,
      mode1: null,
      mode2: null,
      // 日期选择框
      startDate: '',
      endDate: '',
      dateMap,
      optionalArea: optionalArea, // 可选区域
      selectedArea: optionalArea, // 选择的区域
      // score: [],
      cards: {
        score: [],
        area: [],
        mode1: [],
        mode2: [],
        datesList: [],
      },
      cardVisible: false,
      scoreMode: '颜色',
      scoreDetail: {
        visible: false,
        dates: ['100600', '100612', '100700', '100712', '100800', '100812'],
        values: [820, 932, 901, 934, 1290, 1330],
      },
      levels: levels,
      timeSeries: timeSeries,
      options: options,
      cardDescription : {
        show: false,
        loading: false,
        list: [
          {color: colors[0], symbol: symbols[0],  text: '{1} better than {2} statistically significant with {a}% confidence;'},
          {color: colors[1], symbol: symbols[1],  text: '{1} better than {2} statistically significant with {b}% confidence;'},
          {color: colors[2], symbol: symbols[2],  text: '{1} better than {2} statistically significant with {c}% confidence;'},
          {color: colors[3], symbol: symbols[3], text: 'difference between {1} and {2} statistically insignificant;'},
          {color: colors[4], symbol: symbols[4], text: '{1} worse than {2} statistically significant with {c}% confidence;'},
          {color: colors[5], symbol: symbols[5], text: '{1} worse than {2} statistically significant with {b}% confidence;'},
          {color: colors[6], symbol: symbols[6], text: '{1} worse than {2} statistically significant with {a}% confidence;'},
        ]
      },
      isFullscreen: false,
      confidence: {
        a: 98.8,
        b: 96.4,
        c: 88.5,
      },
    }
  },
  mounted(){
    this.getDate();
    this.getConfidence();
  },
  methods: {
    getDate(){
      pageLoadInfo().then(({data}) => {
        for (let i = 0; i < data.mode_list.length; ++i) {
          const mode = data.mode_list[i];
          this.dateMap[mode] = data.dates_list[i];
        }
        this.pageLoading = false;
      }).catch(err => {
        this.pageLoading = false;
      });
    },
    showConfidence() {
      this.cardDescription.show = true;
      this.cardDescription.loading = true;
      this.getConfidence().finally(() => this.cardDescription.loading = false);
    },
    getConfidence() {
      return scdCardGetConfidence().then(({data}) => {
        console.log(data);
        this.confidence = {
          a: data.confidence_a * 100,
          b: data.confidence_b * 100,
          c: data.confidence_c * 100,
        }
      })
    },
    // 获取日期范围，用于获取评分卡的参数
    getDateRange() {
      let startIndex = this.dateOptions.indexOf(this.startDate);
      let endIndex = this.dateOptions.indexOf(this.endDate);
      if (startIndex === -1 || endIndex === -1) {
        return [];
      }
      return this.dateOptions.slice(startIndex, endIndex + 1);
    },
    async getScore(){
      if (this.selectedArea.length === 0) {
        this.$message({
          message: '请输入至少选择一个区域',
          type: 'warning'
        });
        return false;
      }
      if(this.mode1 === this.mode2) {
        this.$message({
          message: '请选择不同的模式',
          type: 'warning'
        });
        return false;
      }
      const dateRange = this.getDateRange();
      if (!dateRange || dateRange.length === 0) {
        this.$message({
          message: '请选择合法日期范围',
          type: 'warning'
        });
        return false;
      }
      const { data: tempScore } = await scdCard({
        mode1: this.mode1,
        mode2: this.mode2,
        datesList: dateRange,
      });

      console.log("data 转换后", tempScore);

      const fixedArea = ['China_an(15-60,70-145)', 'China_obs(15-60,70-145)'];

      for (let i = 0; i < fixedArea.length; ++i) {
        this.cards.area.push(fixedArea[i]);
        this.cards.score.push(tempScore[i]);
        this.cards.mode1.push(this.mode1);
        this.cards.mode2.push(this.mode2);
        this.cards.datesList.push(dateRange);
      }

      return true;
    },
    async addCard() {
      this.loading = true;
      this.cardVisible = true;
      if(!await this.getScore()) {
        this.cardVisible = false;
        this.loading = false;
        return;
      }
      this.$nextTick(() => {
        const h = this.$refs["cards-box"].clientHeight + 10;
        this.$refs["drawing-board"].style.height = h + "px";
      })
      this.loading = false;
    },
    async refreshCard() {
      const keys = Object.keys(this.cards);
      keys.forEach(key => this.cards[key] = []);
      await this.addCard();
    },
    exportPrepare() {
      return this.getConfidence().then(() => {
        this.$refs['desc-bottom'].style.display = 'block'
      });
    },
    exportFinish() {
      this.$refs['desc-bottom'].style.display = 'none';
    },
    changeArea(area) {
      this.title = area;
    },
    fullscreen() {
      this.isFullscreen = true;
    }
  },
  computed: {
    cardWidth() {
      let len = this.cards.score.length;
      let width;
      if(this.isFullscreen) {
        width = document.body.clientWidth * 0.96 - 80;
      } else {
        width = this.$refs['content'].clientWidth - 190;
      }
      let res = width / len;
      return res + "px";
    },
    descFilter() {
      return function(desc) {
        desc = desc.replace('{1}', this.mode1);
        desc = desc.replace('{2}', this.mode2);
        desc = desc.replace('{a}', this.confidence.a);
        desc = desc.replace('{b}', this.confidence.b);
        desc = desc.replace('{c}', this.confidence.c);
        return desc;
      }
    },
    dateOptions() {
      const mode1_dates = new Set(this.dateMap[this.mode1]);
      const mode2_dates = new Set(this.dateMap[this.mode2]);
      const dates = new Set([...mode1_dates].filter(date => mode2_dates.has(date)));
      return [...dates];
    },
  },
  watch: {
    dateOptions(val) {
      if (val.length === 0) {
        this.startDate = '';
        this.endDate = '';
      } else {
        this.startDate = val[0];
        this.endDate = val[val.length - 1];
      }
    },
    dateMap: {
      handler(val) {
        const modes = Object.keys(val);
        if (modes.length === 0) {
          this.mode1 = null;
          this.mode2 = null;
          return;
        }
        this.mode1 = modes[0];
        this.mode2 = modes[1];
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/DFcontent.scss';
.mask {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 5;
}
.drawing-board {
  overflow: scroll;
  background-color: #FFFFFF;
  .card {
    min-width: 400px;
    display: inline-block;

    border-right: 1px solid #DCDFE6;
    &:last-child {
      border-right: none
    }
  }
  &.fullscreen {
    position: fixed !important;
    height: 92% !important;
    width: 96% !important;
    top: 4% !important;
    left: 2% !important;
    z-index: 6;
  }
}
.el-input {
  width: auto !important;
}
.desc-line {
  display: flex;
  div {
    display: inline-block;
    line-height: 2em;
  }
  .desc-color, .desc-symbol {
    height: 1.5em;
    width: 1.5em;
    margin: 2px;
    border-radius: 3px;
    margin-right: 10px;
  }
  .desc-symbol {
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
  }
  &:last-child {
    padding-bottom: 10px;
  }
}
.desc-btn {
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  &:hover {
    color: #409EFF
  }
}
#cards-box {
  width: auto ;
  display: inline-block;
  position: absolute;
  left: 0;
  top: 0;
  white-space: nowrap;
}
</style>